package com.seed.bpmn.engine.common.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>利用jackson的json工具类</p>
 *
 * @author cscz89@126.com
 */
public class JsonUtil {

    private static final Logger LOGGER  = LoggerFactory.getLogger(JsonUtil.class);

    private static ObjectMapper objectMapper = JsonObjectMapperFactory.getInstance()
        .setSerializationInclusion(JsonInclude.Include.NON_NULL);

    /**
     * 将对象转换为JSON字符串
     *
     * @param obj
     * @return
     */
    public static String toJson(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            LOGGER.error("转换为json异常", e);
            throw new IllegalArgumentException("转换为json异常", e);
        }
    }

    /**
     * 将JSON字符串转换为对象
     *
     * @param json
     * @param clazz
     * @return
     */
    public static <T> T parse(String json, Class<T> clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            LOGGER.error("json转换为对象异常", e);
            throw new IllegalArgumentException("json转换为对象异常", e);
        }
    }

    /**
     * 将JSON字符串转换为对象
     *
     * @param json
     * @param valueTypeRef
     * @return
     */
    public static <T> T parse(String json, TypeReference<T> valueTypeRef) {
        try {
            return objectMapper.readValue(json, valueTypeRef);
        } catch (Exception e) {
            LOGGER.error("json转换为对象异常", e);
            throw new IllegalArgumentException("json转换为对象异常", e);
        }
    }

    /**
     * 将JSON字符串转换为对象
     *
     * @param json
     * @param javaType
     * @return
     */
    public static <T> T parse(String json, JavaType javaType) {
        try {
            return objectMapper.readValue(json, javaType);
        } catch (Exception e) {
            LOGGER.error("json转换为对象异常", e);
            throw new IllegalArgumentException("json转换为对象异常", e);
        }
    }

    /**
     * 将JSON字符串转换为对象
     *
     * @param json
     * @param parametrized
     * @param parameterClasses
     * @return
     */
    public static <T> T parse(String json, Class<?> parametrized, Class<?>... parameterClasses) {
        try {
            return parse(json, objectMapper.getTypeFactory().constructParametricType(parametrized,
                parameterClasses));
        } catch (Exception e) {
            LOGGER.error("json转换为对象异常", e);
            throw new IllegalArgumentException("json转换为对象异常", e);
        }
    }
}
